<template>
  <div class="user">
    <page-search
      :search-form-config="searchFormConfig"
      @resetBtnClick="handleResetClick"
      @searchBtnClick="handleQueryClick"
    />
    <page-content
      ref="pageContentRef"
      :content-table-config="contentTableConfig"
      pageName="users"
      @newBtnClick="handleNewBtnClick"
      @editBtnClick="handleEditBtnClick"
    ></page-content>
    <page-modal
      ref="pageModalRef"
      pageName="users"
      :modal-config="modalConfigRef"
      :default-info="defaultInfo"
    ></page-modal>
  </div>
</template>

<script lang="ts">
import { defineComponent, computed } from 'vue'

import { searchFormConfig } from './config/search.config'
import { contentTableConfig } from './config/content.config'
import { modalConfig } from './config/modal.config'

import PageSearch from '@/components/page-search'
import PageContent from '@/components/page-content'
import PageModal from '@/components/page-modal'

import { usePageSearch } from '@/hooks/use-page-search'
import { usePageModal } from '@/hooks/use-page-modal'

import { useStore } from '@/store'

export default defineComponent({
  name: 'users',
  components: {
    PageSearch,
    PageContent,
    PageModal
  },
  setup() {
    const [pageContentRef, handleResetClick, handleQueryClick] = usePageSearch()

    // pageModal 相关的hook逻辑
    //1. 处理密码的逻辑
    const newCallBack = () => {
      const passwordItem = modalConfig.formItems.find(
        (item) => item.field === 'password'
      )
      passwordItem!.isHidden = false
    }
    const editCallBack = () => {
      const passwordItem = modalConfig.formItems.find(
        (item) => item.field === 'password'
      )
      passwordItem!.isHidden = true
      //! 非空
    }

    //2. 动态的添加部门和角色列表
    const sotre = useStore()
    const modalConfigRef = computed(() => {
      const departmentItem = modalConfig.formItems.find(
        (item) => item.field === 'departmentId'
      )
      departmentItem!.options = sotre.state.entireDepartment.map((item) => {
        return { title: item.name, value: item.id }
      })
      const roleItem = modalConfig.formItems.find(
        (item) => item.field === 'roleId'
      )
      roleItem!.options = sotre.state.entireRole.map((item) => {
        return { title: item.name, value: item.id }
      })

      return modalConfig
    })

    //3. 调用hook获取公共变量和函数
    const [handleNewBtnClick, handleEditBtnClick, pageModalRef, defaultInfo] =
      usePageModal(newCallBack, editCallBack)

    return {
      pageContentRef,
      searchFormConfig,
      contentTableConfig,
      handleResetClick,
      handleQueryClick,
      modalConfigRef,
      pageModalRef,
      handleNewBtnClick,
      handleEditBtnClick,
      defaultInfo
    }
  }
})
</script>

<style scoped></style>
